package com.lgw.coupon.service.impl;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.RandomUtil;
import com.lgw.commons.constant.RedisKeyConstant;
import com.lgw.commons.model.pojo.CouponTemplate;
import com.lgw.coupon.config.RedisTemplateConfiguration;
import com.lgw.coupon.mapper.CouponTemplateMapper;
import com.lgw.coupon.service.IAsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.scanner.ScannerImpl;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
public class AsyncServiceImpl implements IAsyncService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CouponTemplateMapper couponTemplateMapper;

    /**
     * 根据模板异步的创建优惠券码
     *
     * @param template
     */
    @Async("getAsyncExecutor")
    @Override
    public void asyncConstructCouponByTemplate(CouponTemplate template) {

        Set<String> couponCodes = buildCouponCode(template);
        //coupon_template_code:1
        String redisKey = RedisKeyConstant.coupon_template_code.getKey() + template.getId().toString();
        //放入redis中
        log.info("Push CouponCode To Redis: {}",redisTemplate.opsForList().rightPushAll(redisKey,couponCodes));
        //优惠卷模板已经生成
        template.setIsValid(1);
        couponTemplateMapper.updateValid(template.getId());
    }

    /**
     * 构建优惠卷码   类型(1) - 日期(190101) - (随机10位数,第一位不为0)1023456780)
     * 前四位：类型
     * 中间六位：日期随机
     * 后十位：0-9的随机数
     *
     * @param template
     * @return
     */
    private static Set<String> buildCouponCode(CouponTemplate template) {
        Set<String> result = new HashSet<>();
        String prefix4 = template.getCategory();
        while (prefix4.length() < 4) {
            prefix4 = "0" + prefix4;
        }
        //中间六位
        String date = new SimpleDateFormat("yyMMdd").format(template.getCreateDate());

        while (result.size() < template.getCouponCount()) {
            result.add(prefix4 + date + +RandomUtil.randomInt(1,10) + RandomUtil.randomNumbers(9));
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(RedisKeyConstant.coupon_template_code);
        System.out.println(RedisKeyConstant.verify_code.getKey());
        String c = "dqwdqwdqwd:";
        String b = RedisKeyConstant.verify_code.getKey();
        System.out.println(b);
        System.out.println(RedisKeyConstant.coupon_template_code);
    }
}
